package com.fmdj.odr.quartz;

import cn.hutool.core.map.MapUtil;
import com.codingapi.txlcn.common.exception.TCGlobalContextException;
import com.fmdj.common.exception.GlobalException;
import com.fmdj.common.wxpay.MyWXPayConfig;
import com.fmdj.common.wxpay.WXPay;
import com.fmdj.common.wxpay.WXPayConstants;
import com.fmdj.common.wxpay.WXPayUtil;
import com.fmdj.odr.db.dao.OrderProfitsharingDao;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SearchProfitsharingJob extends QuartzJobBean {

    @Autowired
    private OrderProfitsharingDao orderProfitsharingDao;

    @Autowired
    private MyWXPayConfig myWXPayConfig;

    @Autowired
    private QuartzUtil quartUtil;
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        //从context中拿出业务数据 jobdetail
        Map map = context.getJobDetail().getJobDataMap();
        String uuid = MapUtil.getStr(map, "uuid");
        long profitsharingId = MapUtil.getLong(map, "profitsharingId");
        String payId = MapUtil.getStr(map, "payId");

        //查询分账结果
        try{
            //创建微信支付对象
            WXPay wxPay = new WXPay(myWXPayConfig);

            //构造请求参数
            HashMap params = new HashMap<>(){{
                put("mch_id", myWXPayConfig.getMchID());
                put("nonce_str", WXPayUtil.generateNonceStr());
                put("transaction_id", payId);
                put("out_order_no", uuid);
            }};

            //构建数字签命
            String sign = WXPayUtil.generateSignature(params, myWXPayConfig.getKey(), WXPayConstants.SignType.HMACSHA256);
            params.put("sign", sign);
            //无论收还是发 得到的结果都是xml
            String url = "/pay/profitsharingQuery";
            String response = wxPay.requestWithCert(url, params, 3000, 3000);
            System.out.println(response);
            //验证响应中的数字签命
            if (WXPayUtil.isSignatureValid(response, myWXPayConfig.getKey(), WXPayConstants.SignType.HMACSHA256)) {
                //验证成功,参数没有被修改
                Map date = wxPay.processResponseXml(response);
                String returnCode = MapUtil.getStr(date, "return_code");
                String resultCode = MapUtil.getStr(date, "result_code");

                if ("SUCCUSS".equals(returnCode) && "SUCCESS".equals(resultCode)) {
                    String status = MapUtil.getStr(date, "status");
                    if ("FINISHED".equals(status)) {
                        //更新分账状态
                        int rows = orderProfitsharingDao.updateProfitSharingStatus(profitsharingId);
                        if (rows!=1) {
                            log.error("更新分账状态失败",new TCGlobalContextException("更新分账状态失败"));
                        }
                    }else{
                        throw new GlobalException("查询微信分账结果状态失败");
                    }
                }else {
                    log.error("微信分账失败",new GlobalException("微信分账失败"));
                }
            }else {
                log.error("验证数字签命失败",new GlobalException("验证数字签命失败"));
            }
        } catch (Exception e) {
            log.error("查询分账状态失败");
            throw new RuntimeException(e);
        }
    }
}
